package com.kele.controller;


import com.alibaba.fastjson.JSON;
import com.kele.direct.UserDirect;
import com.kele.entity.User;
import com.kele.service.impl.UserServiceImpl;
import com.kele.utils.R;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author kele
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    UserServiceImpl userService;

    @Autowired
    UserDirect userDirect;

    User user;

    @GetMapping("/findAll")
    public R findAll(){

        List<User> userList = userService.findAll();

        if (userList.size()!=0){
            return R.ok(200,"查找全部用户信息成功").put("data",userList);
        }

        return R.error(404,"没有找到用户信息");

    }

    @GetMapping("/findById/{id}")
    public R findById(@PathVariable("id") Integer id){

        User user = userService.findUserById(id);

        if (user!=null){
            return R.ok(200,"通过ida查找用户信息").put("data",user);
        }

        return R.error(404,"没有找到用户信息");

    }
    @PutMapping("/update/{id}")
    public R updateUser(@PathVariable("id") Integer id){

        User user1 = userService.findUserById(id);
        user1.setName("kele");
        user1.setSex("men");

        int i = userService.updateUser(user1);
        if (i>0){
            return R.ok(200,"修改成功");
        }
        return R.error(200,"修改失败");
    }

    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable("id") Integer id){

        int i = userService.deleteUser(id);
        if (i>0){
            return R.ok(200,"删除成功");
        }

        return R.error(200,"删除失败");
    }

    @PostMapping("/insert")
    public R insertUser(){

        User addUser=new User();
        addUser.setName(user.getName());
        addUser.setSex(user.getSex());

        int i = userService.insertUser(addUser);
        if(i>0){
            return R.ok(200,"新增成功");

        }
        return R.error(200,"新增失败");
    }

    /**
     * 创建接受消息的方法
     *@RabbitHandler 表示消息的落脚点
     */

    @RabbitListener(queues = {"user.direct.queue"})
    public void receiveMsg(Message msg){

        user = JSON.parseObject(msg.getBody(), User.class);

        System.out.println("user direct ---接收到了要增加的信息是: "+user);


    }


}
